package com.epita.mgdc;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MGDCActivity extends Activity {
	/** Called when the activity is first created. */
	ListView lvListe;
	
	Cursor cursor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contactlist);

		cursor = getContacts();
		
		lvListe = (ListView) findViewById(R.id.lvListe);
		
		List<String> contacts = new ArrayList<String>();
		
		while (cursor.moveToNext()) {
			contacts.add(cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));
		}
		
		lvListe.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, contacts.toArray(new String[0])));
		
		lvListe.setOnItemClickListener(new OnItemClickListener() {
			    public void onItemClick(AdapterView<?> parent, View view,
			        int position, long id) {
			    	 Intent myIntent = new Intent(view.getContext(), ContactActivity.class);
			    	 Bundle objetbunble = new Bundle();
			    	 cursor.moveToPosition(position);
			    	 objetbunble.putString("contactID",cursor.getString(cursor.getColumnIndex(ContactsContract.Data._ID)));
			    	 myIntent.putExtras(objetbunble);
	                 startActivityForResult(myIntent, 0);
			    }
			  });
	}
	
	private Cursor getContacts() {
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME };
		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
				+ ("1") + "'";
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
				+ " COLLATE LOCALIZED ASC";

		return managedQuery(uri, projection, selection, selectionArgs,
				sortOrder);
	}

}
